const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const fs = require('fs');
const jimp = require('jimp');
const magic = require('stream-mmmagic');

const prefix = '/api/file';

module.exports = app => {
    const {router, middleware} = app;

    //返回自由上传的文件
    router.get('/file/:file', async ctx => {
        let file = ctx.params.file;
        file = await app.model.File.findOne({raw: true, where: {file}});
        if (!file)
            return ctx.helper.notFound('不存在的文件');
        file.stream = fs.createReadStream(app.config.screenshot.path + '/' + file.file);
        // ctx.body = {stream: file.stream};
        console.log({file});
        ctx.helper.file(file);
    });

    /**删除上传的文件*/
    router.del('/file/:file', middleware.api(2), async ctx => {
        let file = ctx.params.file;
        file = await app.model.File.findOne({where: {file}});
        if (!file)
            return ctx.helper.notFound('不存在的文件');
        file.update({deleted: true});
        ctx.body = 'ok';
    });

    //获取单一主播截图记录
    router.get(prefix + '/anchor/:image_id', async ctx => {
        ctx.body = await ctx.app.model.File.findByPk(ctx.params.image_id);
    });

    //获取单一平台截图记录
    router.get(prefix + '/platform/:image_id', async ctx => {
        ctx.body = await ctx.app.model.File.findByPk(ctx.params.image_id);
    });

    const uploadMiddleware = async (ctx, next) => {
        const {schedule_id} = ctx.params;
        const schedule = await ctx.app.model.DetailAnchorSchedule.findByPk(schedule_id);
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');
        ctx.schedule = schedule;

        const stream = await ctx.getFileStream();

        if (stream.mimeType.indexOf('image') !== 0)
            return ctx.helper.error('只接受图片文件');

        const now = Date.now();
        const dir = app.config.screenshot.path;
        const filename = `${dir}/${now}`;
        const thumbnailPath = `${dir}/${now}_small`;
        try {
            const writeStream = fs.createWriteStream(filename);
            ctx.file = now;
            await awaitWriteStream(stream.pipe(writeStream));
            jimp.read(filename).then(lenna => {
                lenna.scale(0.25).quality(50).getBuffer(jimp.MIME_JPEG, (err, buffer) => {
                    fs.writeFile(thumbnailPath, buffer, () => {
                    });
                });
            });
        } catch (err) {
            await sendToWormhole(output);
            return ctx.helper.error(err.message);
        }
        await next();
    };

    //上传主播截图
    router.post(prefix + '/:schedule_id/upload_anchor', middleware.api(4), uploadMiddleware, async ctx => {
        const {id: schedule_id, anchor_id, platform_id} = ctx.schedule;
        let file = await app.model.File.create({file: ctx.file});
        ctx.app.model.DetailScheduleImage.create({
            file_id: file.id,
            schedule_id,
            platform_id,
            anchor_id,
        });
        ctx.body = file;
    });

    //上传平台硬广截图
    router.post(prefix + '/:schedule_id/upload_platform', middleware.api(4), uploadMiddleware, async ctx => {
        const {platform_id, id: schedule_id} = ctx.schedule;

        let file = await app.model.File.create({file: ctx.file});
        await ctx.app.model.DetailScheduleImage.create({
            file_id: file.id,
            schedule_id,
            platform_id,
        });
        ctx.body = file;
    });
};

/**
 * 获取上传的文件类型
 * @param stream
 * @returns {Promise<any>}
 */
async function mmmagic(stream) {
    return new Promise((resolve, reject) => {
        magic(stream, (err, mime, output) => {
            if (err)
                return reject(err);
            resolve({mime, output});
        });
    });
}